package com.zhangchuchu.neohealth.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhangchuchu.neohealth.common.R;
import com.zhangchuchu.neohealth.entity.User;
import com.zhangchuchu.neohealth.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
@CrossOrigin(origins = "*") // 允许跨域请求
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody User user, HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();
        // 判断前端传递的数据是否合法
        if (user.getUsername() == null || user.getPassword() == null || user.getEmail() == null || user.getPhone() == null) {
            response.put("code", 400);
            response.put("message", "缺少必要的字段");
            return response;
        }

        // 校验用户名、邮箱、手机号是否已存在
        if (userService.existsByUsername(user.getUsername())) {
            response.put("code", 400);
            response.put("message", "用户名已存在");
            return response;
        }

        if (userService.existsByEmail(user.getEmail())) {
            response.put("code", 400);
            response.put("message", "邮箱已存在");
            return response;
        }

        if (userService.existsByPhone(user.getPhone())) {
            response.put("code", 400);
            response.put("message", "手机号已存在");
            return response;
        }


        if (user.getStatus() == null) {
            user.setStatus(user.getStatus());
        }
        if (user.getRole() == null) {
            user.setRole(user.getRole());
        }
        if (user.getPermissionLevel() == null) {
            user.setPermissionLevel(user.getPermissionLevel());
        }
        if (user.getSex() == null) {
            user.setSex(user.getSex());
        }

        if (user.getCreatedTime() == null) {
            user.setCreatedTime(user.getCreatedTime());
        }
        if (user.getUpdatedTime() == null) {
            user.setUpdatedTime(user.getUpdatedTime());
        }
        if (user.getLastLoginTime() == null) {
            user.setLastLoginTime(user.getLastLoginTime());
        }

        // 保存用户到数据库
        boolean saved = userService.save(user);
        if (saved) {
            response.put("code", 200);
            response.put("message", "注册成功");
            response.put("data", user);
        } else {
            response.put("code", 500);
            response.put("message", "注册失败");
        }

        HttpSession session = request.getSession();
        session.setAttribute("user", user);
        return response;
    }

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody User user, HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();

        // 判断前端传递的数据是否合法
        if (user.getUsername() == null && user.getEmail() == null && user.getPhone() == null) {
            response.put("code", 400);
            response.put("message", "手机号、邮箱或用户名不能为空");
            return response;
        }

        // 校验手机号、邮箱或用户名是否存在
        User existingUser = null;
        if (user.getUsername() != null) {
            existingUser = userService.findByUsername(user.getUsername());
        } else if (user.getEmail() != null) {
            existingUser = userService.findByEmail(user.getEmail());
        } else if (user.getPhone() != null) {
            existingUser = userService.findByPhone(user.getPhone());
        }

        if (existingUser == null) {
            response.put("code", 400);
            response.put("message", "该用户未注册");
            return response;
        }

        // 校验密码是否正确
        if (!existingUser.getPassword().equals(user.getPassword())) {
            response.put("code", 400);
            response.put("message", "密码错误");
            return response;
        }

        // 更新最后登录时间
        existingUser.setLastLoginTime(user.getLastLoginTime()); // 或者使用用户传递的更新时间
        userService.updateUser(existingUser);

        // 返回登录成功的响应
        response.put("code", 200);
        response.put("message", "登录成功");
        response.put("data", existingUser);

        HttpSession session = request.getSession();
        session.setAttribute("user", existingUser);

        return response;
    }

    /**
     * 查询所有数据（不分页）
     */
    @GetMapping("/getList")
    public R<List<User>> selectList() {
        return R.success(userService.list());
    }


    /**
     * 分页查询所有数据
     *
     * @param page 分页对象
     * @return 所有数据
     */
    @GetMapping()
    public R<Page<User>> selectAll(@RequestParam int page, @RequestParam int size, User user) {
        Page<User> pageObj = new Page<>(page, size);
        return R.success(this.userService.page(pageObj, new QueryWrapper<>(user)));
    }
    /**
     * 通过主键查询单条数据
     */
    @GetMapping("{id}")
    public R<User> selectOne(@PathVariable Serializable id) {
        return R.success(userService.getById(id));
    }

    /**
     * 新增数据
     */
    @PostMapping
    public R<Boolean> insert(@RequestBody User User) {
        return R.success(userService.save(User));
    }

    /**
     * 修改数据
     */
    @PutMapping
    public R<Boolean> update(@RequestBody User User) {
        return R.success(userService.updateById(User));
    }

    /**
     * 删除数据（批量）
     */
    @DeleteMapping
    public R<Boolean> delete(@RequestParam("idList") List<Integer> idList) {
        return R.success(userService.removeByIds(idList));
    }

    /**
     * 条件查询
     */
    @GetMapping("/searchList")
    public R<Page<User>> selectList(@RequestParam(value = "query", required = false) String query,@RequestParam int page, @RequestParam int size) {

        Page<User> page1 = new Page<>(page,size);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        // 如果查询条件存在，则加入查询条件
        if (query != null && !query.trim().isEmpty()) {
            queryWrapper.like("nickname", query)  // 假设根据标题进行模糊查询
                    .or().like("username", query);  // 也可以根据内容进行模糊查询
        }
        return R.success(userService.page(page1,queryWrapper));
    }

}
